package com.ruoyi.mobile.project.task;

import com.ruoyi.db.oms.domain.OmsOrder;
import com.ruoyi.mobile.system.SystemConfig;
import com.ruoyi.mobile.project.oms.service.WxOmsOrderService;
import com.ruoyi.mobile.task.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

//@Component   //因为运行出错，暂时关了？？？？？？？？？？？
public class TaskStartupRunner implements ApplicationRunner
{
    @Autowired
    private WxOmsOrderService orderService;

    @Autowired
    private TaskService taskService;

    @Override
    public void run(ApplicationArguments args) throws Exception
    {
        List<OmsOrder> orderList = orderService.queryUnpaid(SystemConfig.getOrderUnpaid());
        for (OmsOrder order : orderList)
        {
            LocalDateTime add = order.getAddTime();
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime expire = add.plusMinutes(SystemConfig.getOrderUnpaid());
            if (expire.isBefore(now))
            {
                // 已经过期，则加入延迟队列
                taskService.addTask(new OrderUnpaidTask(order.getId(), 0));
            }
            else
            {
                // 还没过期，则加入延迟队列
                long delay = ChronoUnit.MILLIS.between(now, expire);
                taskService.addTask(new OrderUnpaidTask(order.getId(), delay));
            }
        }
    }
}
